import { useEffect, useRef, useState, useCallback, useMemo } from "react";

function useDropInfo(id, callabck, list) {
  const nodesRef = useRef(null);
  const placeholderRef = useRef(null);
  const resultDataRef = useRef({});
  useEffect(() => {
    nodesRef.current = document.getElementById(id);
  }, [id]);

  const getNodes = useCallback(() => {
    if (!nodesRef?.current) return [];

    const nodeContainer = nodesRef?.current;
    const nodes = nodeContainer.children;
    return nodes;
  }, [nodesRef, list]);

  //移除占位元素
  const removePlaceholderEle = () => {
    const removeEle = document.getElementById("drag-ele-placeholder");

    if (!nodesRef?.current || !removeEle) {
      return;
    }
    nodesRef.current.removeChild(removeEle);
  };

  //创建占位元素
  const createElePlaceholder = (() => {
    let ele = null;
    return () => {
      if (!ele) {
        ele = document.createElement("div");
        ele.setAttribute("id", "drag-ele-placeholder");
        ele.innerHTML = `<div style="width: 100%; height:50px; position: relative">
            <div style="width: 150px; height: 40px; text-align: center; position: absolute;
            left: 0; right: 0; top: 0; bottom:0; margin: auto; background: #878; line-height: 40px">放置组件</div>
          </div>`;
      }

      return ele;
    };
  })();
  const onMessage = (e) => {
    const { x, y, isRemove, isAdd, addId, type } = e?.data;
    if (type !== 1) return;
    if (isRemove) {
      if (placeholderRef.current && isAdd) {
        callabck && callabck({ ...resultDataRef.current, addId });
        resultDataRef.current = {};
        placeholderRef.current = false;
      }
      removePlaceholderEle();
      return;
    }
    if (x <= 0 && y <= 0) {
      return;
    }
    const el = createElePlaceholder();
    if (!el) return;
    placeholderRef.current = el;

    const nodes = getNodes();
    if (!nodes.length) {
      nodesRef.current.appendChild(el);
      resultDataRef.current = { index: 0, isBefore: true };
      return;
    }
    for (let i = 0; i < nodes.length; i++) {
      const item = nodes[i];

      const { left, top, height, width } = item.getBoundingClientRect();
      if (x > left && x < left + width && y > top && y <= top + height / 2) {
        item.before(el);
        resultDataRef.current = { index: i, isBefore: true };
        return;
      }
      if (
        x >= left &&
        x < left + width &&
        y > top + height / 2 &&
        y <= top + height
      ) {
        resultDataRef.current = { index: i, isBefore: false };
        item.after(el);
        return;
      }
    }
  };
  useEffect(() => {
    window.addEventListener("message", onMessage);
    return () => {
      window.removeEventListener("message", onMessage);
    };
  }, [id]);
}
export default useDropInfo;
